package com.dtjd.playcoinmonkey.activities;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;

import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.adapter.HomeListAdapter;
import com.dtjd.playcoinmonkey.bean.HomeListBean;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.ActivitySearchBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SearchActivity extends AppCompatActivity {
    private HomeListAdapter adp;
    private int current=1;
    private final List<HomeListBean> data=new ArrayList<>();
    private String query="";
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){finish();}
        return super.onOptionsItemSelected(item);
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        @NonNull ActivitySearchBinding binding = ActivitySearchBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        adp=new HomeListAdapter(this, data, (v, position) -> {

        }, (v, position) -> {

        }, (v, position) -> {

        });
        binding.searchList.setAdapter(adp);
        binding.searchSearchView.setIconified(false);
        binding.searchSearchView.onActionViewExpanded();
        binding.searchSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String q) {
                query=q;
                refresh(true,null,null);
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        binding.searchRefresh.setRefreshHeader(new ClassicsHeader(this));
        binding.searchSearchView.setSubmitButtonEnabled(true);
        binding.searchRefresh.setRefreshFooter(new ClassicsFooter(this));
        binding.searchRefresh.setOnRefreshListener(refreshLayout -> refresh(true,refreshLayout,null));
        binding.searchRefresh.setOnLoadMoreListener(refreshLayout -> refresh(false,null,refreshLayout));
        binding.searchList.setOnItemClickListener((adapterView, view, i, l) -> {
            MyApplication.postBean=data.get(i);
            startActivity(new Intent(this,PostDetailActivity.class));
        });
    }
    private void refresh(boolean isRefresh,RefreshLayout refreshLayout, RefreshLayout loadmorelayout) {
        if (isRefresh){
            current=1;
            data.clear();
        }else {
            current++;
        }
        List<HttpParaBean> para=new ArrayList<>();
        para.add(new HttpParaBean("token","token"));
        para.add(new HttpParaBean("keyword",query));
        para.add(new HttpParaBean("current",String.valueOf(current)));
        para.add(new HttpParaBean("size","5"));
        Network.post(para, "wbhMain/searchPosts", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                runOnUiThread(() -> {
                    try {
                        JSONArray ja = new JSONObject(Objects.requireNonNull(response.body()).string()).getJSONArray("datalist");
                        for (int i = 0; i < ja.length(); i++) {
                            JSONObject jo = ja.getJSONObject(i);
                            JSONArray jo_imgs = jo.getJSONArray("imgs");
                            String img_url="";
                            if (jo_imgs.length()>0) img_url= jo_imgs.getString(0);
                            String bannedCount = "0";
                            if (jo.has("bannedCount")) bannedCount=jo.getString("bannedCount");
                            data.add( new HomeListBean(0,jo.getString("bp_content"), img_url, jo.getString("bp_report"), jo.getString("bp_sort"), jo.getString("bp_title"), jo.getString("bp_type"), jo.getInt("bu_id"), jo.getString("id"), jo.getInt("bp_click_number"), jo.getString("time"), jo.getString("wb_nickname"), jo.getString("wb_url"),bannedCount,null));
                        }
                        adp.notifyDataSetChanged();
                        if (refreshLayout!=null)refreshLayout.finishRefresh(0);
                        if (loadmorelayout!=null)loadmorelayout.finishLoadMore(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
}